# encoding: utf-8
"""
@file: image_bed.py
@desc:
@author: bill-hu
@time: 9/22/2021 
"""
import os
import shutil
import sys
import urllib.request
import uuid
from datetime import datetime

import git

# 本地图床目录
image_dir = 'images'

# 本地git仓
local_git_repo = r'D:\Workspace\PyCharm\ImageBed'

# 图片对应远程链接(注意复制github/gitee内图片地址时，需要将blob改为raw)
url_base = 'https://gitee.com/billhuhongbin/ImageBed/raw/master/%s/%s/%s'

git = git.Repo(local_git_repo).git

if __name__ == '__main__':
    is_upload_net_img = False
    image_files = sys.argv[1:]
    date_str = datetime.strftime(datetime.now(), '%Y-%m-%d')
    temp_dir = os.path.join(local_git_repo, image_dir, date_str)
    if not (os.path.exists(temp_dir) and os.path.isdir(temp_dir)):
        os.makedirs(temp_dir)
    print('Upload Success:')
    for image_file in image_files:
        # 切割路径获取文件名和后缀
        (image_path, image_name) = os.path.split(image_file)
        (file_name, suffix) = os.path.splitext(image_name)

        # 重组文件名
        image_name = 'image-' + str(uuid.uuid4()) + suffix
        new_image_file = os.path.join(temp_dir, image_name)

        if image_file.startswith('http') or image_file.startswith('https'):
            if is_upload_net_img:
                image_file = urllib.request.urlretrieve(image_file, new_image_file)[0]
            else:
                print(image_file)
                continue
        shutil.copy(image_file, new_image_file)
        git.add(new_image_file)
        git.commit('-m', 'Add image: ' + image_name)
        git.push()
        print(url_base % (image_dir, date_str, image_name))
